package com.fengjue.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fengjue.common.RespBean;
import com.fengjue.common.RespPageBean;
import com.fengjue.common.utils.JedisUtil;
import com.fengjue.common.utils.ObjectTranscoder;
import com.fengjue.pojo.*;
import com.fengjue.service.*;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author fengjue
 * @since 2021-03-10
 */
@RestController
@RequestMapping("/system/basic/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IEmployeeEcService employeeEcService;
    @Autowired
    private IPoliticsStatusService politicsStatusService;
    @Autowired
    private IJoblevelService joblevelService;
    @Autowired
    private INationService nationService;
    @Autowired
    private IPositionService positionService;
    @Autowired
    private IDepartmentService departmentService;


    /**
     * @param currentPage    当前页
     * @param size           当前页的条数
     * @param employee       用对象去接收，搜索条件是员工名字，这里也可以单独加一个key
     * @param beginDateScope 开始时间与结束时间，这是个时间段数组
     * @return
     */
    @ApiOperation(value = "获取所有员工(分页)")
    @GetMapping
    public RespPageBean getEmployee(
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer size,
            Employee employee,
            LocalDate[] beginDateScope

    ) {
        return employeeEcService.getEmployeeByPage(currentPage, size, employee, beginDateScope);
    }

    @ApiOperation(value = "添加员工")
    @PostMapping
    public RespBean addEmp(@RequestBody Employee employee) {

        return employeeService.addEmp(employee);


    }

    @ApiOperation(value = "更新员工")
    @PutMapping
    public RespBean updateEmp(@RequestBody Employee employee) {

        boolean b = employeeService.updateById(employee);
        if (b) {
            return RespBean.success("更新成功");
        }

        return RespBean.error("删除失败");

    }


    @ApiOperation(value = "删除员工")
    @DeleteMapping("/{id}")
    public RespBean deleteEmp(@PathVariable Integer id) {
        boolean b = employeeService.removeById(id);
        if (b) {
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }


    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response) {
        // 数据库查询
        List<Employee> list = employeeEcService.getEmployee(null);
        /**
         * title 员工表
         * sheetName 员工表
         * HSSF 2003版本的
         */
        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        // 导出表格
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list);
        ServletOutputStream outputStream = null;
        try {
            response.reset();
            // 流形式
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            // 防止中文乱码
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("员工表", "UTF-8") + ".xls");
            outputStream = response.getOutputStream();
            // 写会
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导入员工数据")
    @PostMapping("/import")
    public RespBean importEmployee(MultipartFile file) {
        ImportParams params = new ImportParams();
        // 去掉标题行
        params.setTitleRows(1);
        // 数据库查询数据
//        List<Nation> nationList = nationService.list();
//        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
//        List<Department> departmentList = departmentService.list();
//        List<Joblevel> joblevelList = joblevelService.list();
//        List<Position> list1 = positionService.list();
        Jedis jedis = JedisUtil.getInstance().getPool().getResource();
        GenericJackson2JsonRedisSerializer gz = new GenericJackson2JsonRedisSerializer();
        //Jedis resource = JedisUtil.getInstance().getPool().getResource();
        //        GenericJackson2JsonRedisSerializer gz = new GenericJackson2JsonRedisSerializer();
        //        final String s = "menusWithRole";
        //        byte[] menusWithRoleS = gz.serialize(s);
        //        byte[] bytes = resource.get(menusWithRoleS);
        //        if(bytes==null){
        //            List<Menu> allMenus = menuMapper.getMenusWithRole();
        //            byte[] serialize = gz.serialize(allMenus);
        //            resource.set(menusWithRoleS,serialize);
        //            return allMenus;
        //        }
        //        List<Menu> deserialize = (List<Menu>) gz.deserialize(bytes);
        //        resource.close();
        //        return deserialize;


        List<Employee> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            list.forEach(employee -> {


                        byte[] nbyte = jedis.get(gz.serialize(employee.getNation().getName()));
                        byte[] dbyte = jedis.get(gz.serialize(employee.getDepartment().getName()));
                        byte[] pbyte = jedis.get(gz.serialize(employee.getPoliticsStatus().getName()));
                        String jname = employee.getJoblevel().getName();
                        byte[] jBytes = jedis.get(gz.serialize(jname));

                        String pName = employee.getPosition().getName();
                        byte[] pBytes = jedis.get(gz.serialize(pName));


                        // 通过民族获取id
                        // 如果为空，则直接到数据库查询，通过name查询对应id，返回id，并存储两个数据，k为民族，值为id
                        if (nbyte == null) {
                            Nation nation = nationService.getOne(new QueryWrapper<Nation>().eq("name", employee.getNation().getName()));
                            Integer id = nation.getId();
                            jedis.set(gz.serialize(employee.getNation().getName()), gz.serialize(id));
                            employee.setNationId(id);
                            jedis.close();
                        }
                        Integer i = (Integer) gz.deserialize(nbyte);
                        employee.setNationId(i);

                        // 通过部门名称获取id
                        if (dbyte == null) {
                            Department department = departmentService.getOne(new QueryWrapper<Department>().eq("name", employee.getDepartment().getName()));
                            Integer id = department.getId();
                            employee.setDepartmentId(id);
                            jedis.set(gz.serialize(employee.getDepartment().getName()), gz.serialize(id));
                            jedis.close();

                        }
                        Integer i2 = (Integer) gz.deserialize(dbyte);
                        employee.setDepartmentId(i2);

                        // 通过政治面貌获取id
                        if (pbyte == null) {
                            PoliticsStatus politicsStatus = politicsStatusService.getOne(new QueryWrapper<PoliticsStatus>().eq("name", employee.getPoliticsStatus().getName()));
                            Integer id = politicsStatus.getId();
                            employee.setPoliticId(id);
                            jedis.set(gz.serialize(employee.getPoliticsStatus().getName()), gz.serialize(id));
                            jedis.close();
                        }
                        Integer i3 = (Integer) gz.deserialize(pbyte);
                        employee.setPoliticId(i3);


                        // 通过职称jname获取id
                        if (jBytes == null) {
                            Joblevel joblevel = joblevelService.getOne(new QueryWrapper<Joblevel>().eq("name", jname));
                            Integer id = joblevel.getId();
                            employee.setJobLevelId(id);
                            jedis.set(gz.serialize(joblevel.getName()), gz.serialize(id));
                            jedis.close();

                        }
                        Integer i4 = (Integer) gz.deserialize(jBytes);
                        employee.setJobLevelId(i4);

                        // 通过职位pname获取id
                        if (pBytes == null) {
                            Position position = positionService.getOne(new QueryWrapper<Position>().eq("name", pName));
                            Integer id = position.getId();
                            employee.setPosId(id);
                            jedis.set(gz.serialize(position.getName()), gz.serialize(id));
                            jedis.close();
                        }
                        Integer i5 = (Integer) gz.deserialize(pBytes);
                        employee.setPosId(i5);
                    }

            );
            if (employeeService.saveBatch(list)) {
                return RespBean.success("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RespBean.error("导入失败");
        }
        return RespBean.error("导入失败");


    }


    @ApiOperation("获取所有政治面貌")
    @GetMapping("/politicsStatus")
    public List<PoliticsStatus> getAllPoliticsStatus() {
        Jedis jedis = JedisUtil.getInstance().getJedis();
        String s = new String("plist");
        byte[] plist = jedis.get(ObjectTranscoder.serialize(s));
        if (plist == null) {
            List<PoliticsStatus> list = politicsStatusService.list();
            byte[] serialize = ObjectTranscoder.serialize(list);
            jedis.set(ObjectTranscoder.serialize(s), serialize);
            return list;
        }
        List<PoliticsStatus> listp = (List<PoliticsStatus>) ObjectTranscoder.deserialize(plist);
        return listp;
    }

    @ApiOperation(value = "获取所有职称")
    @GetMapping("/joblevel")
    public List<Joblevel> getAllJoblevels() {
        return joblevelService.list();
    }


    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nation")
    public List<Nation> getAllNations() {
        return nationService.list();
    }

    @ApiOperation(value = "获取所有职位")
    @GetMapping("/position")
    public List<Position> getAllPositions() {
        return positionService.list();
    }

    @ApiOperation(value = "获取所有部门")
    @GetMapping("/deps")
    public List<Department> getAllDepartment() {
        return departmentService.getAllDepartments();
    }

    @ApiOperation(value = " 获取工号")
    @GetMapping("/maxWorkID")
    public RespBean maxWorkID() {
        return employeeEcService.maxWorkID();
    }


}
